import { EBundleType, EViewType } from "../../../Script/Common/Enum";
import { IViewData } from "../../../Script/Interface/IMessage";
import { SceneGame } from "../../../Script/SceneGame";
import AppService from "../../../Script/Service/AppService";
import GameUtil from "../../../Script/Util/GameUtil";
import StorageUtil from "../../../Script/Util/StorageUtil";
import BaseSprite from "../../Base/BaseSprite";
import TaskModule from "../../Common/TaskModule";
import AudioManager, { EMusicType } from "../../Util/AudioManager";
import GameUI from "../GameUI";
import HomeUI from "../home/HomeUI";

const { ccclass, property } = cc._decorator;

interface ISyringeConfig {
    id: number;
    min: number;
    max: number;
}

const VIEW_DATA: IViewData = {
    name: 'SyringeUI',
    type: EViewType.Panel,
    bundle: EBundleType.Game,
    zIndex: 100,
};

/** 打针(治病)小玩法 */
@ccclass
export default class SyringeUI extends BaseSprite {

    @property({ type: sp.Skeleton, tooltip: "顾母动画" })
    private gumuSke: sp.Skeleton = null;
    @property({ type: sp.Skeleton, tooltip: "手动画" })
    private ske: sp.Skeleton = null;

    @property({ type: [cc.Node], tooltip: "心" })
    private xins: cc.Node[] = [];
    @property({ type: [cc.Node], tooltip: "进度条色块" })
    private colors: cc.Node[] = [];
    @property({ type: cc.Node, tooltip: "箭头" })
    private arrow: cc.Node = null;
    @property({ type: cc.Node, tooltip: "扎针按钮" })
    private btnStart: cc.Node = null;

    @property({type: cc.Node, tooltip: "提示"})
    private labTip: cc.Node = null;

    private hp: number = 3;
    private curSpeed: number = 10;
    private countTime: number = 0;
    private changeTime: number = 60;
    private isRigthDir: boolean = true;
    private color: cc.Node = null;
    private isMove: boolean = false;

    private configs: ISyringeConfig[] = [
        { id: 1, min: 5, max: 10 },
        { id: 2, min: 7, max: 10 },
        { id: 3, min: 7, max: 12 },
        { id: 4, min: 10, max: 10 },
        { id: 5, min: 10, max: 12 },
    ]
    private curId: number = 1;
    private config: ISyringeConfig = null;

    protected onLoad() {
        super.onLoad();

        AudioManager.instance.playMusic(EMusicType.SyringeBgm);

        cc.tween(this.labTip).repeat(2,
            cc.sequence(
                cc.fadeIn(0),
                cc.fadeOut(0.1),
                cc.delayTime(0.3),
                cc.fadeIn(0.1),
                cc.delayTime(0.3),
            )
        ).start();

        this.hp = 3;
        this.curId = 1;
        this.init();
    }

    private init() {
        this.isMove = true;
        this.btnStart.active = true;
        
        this.config = this.configs.find((o) => o.id === this.curId);
        this.curSpeed = GameUtil.getRandomInteger(this.config.min, this.config.max);
        this.arrow.x = -280;
        this.colors.forEach((o, i) => {
            o.active = false;
        });
        this.color = this.colors[this.curId - 1];
        this.color.x = GameUtil.getRandomInteger(-200, 200);
        this.color.active = true;

        this.refreshHp();
        this.setArrowSpeed();
        this.setAttachment();
    }

    private setArrowSpeed() {
        // this.curSpeed = Math.floor(Math.random() * (this.maxSpeed - this.minSpeed) + this.minSpeed);
    }

    private setAttachment(isFail: boolean = false) {
        const attach = !isFail ? "头 待机" : "痛苦表情";
        this.gumuSke.setAttachment('头 待机', attach);
    }

    private refreshHp() {
        for (let i = this.xins.length - 1; i > -1; i--) {
            this.xins[i].active = this.hp > i;
        }
    }

    protected update(dt: number) {
        if (!this.isMove) return;
        if (this.countTime >= this.changeTime) {
            this.countTime = 0;
            this.setArrowSpeed();
        }
        if (this.isRigthDir) {
            this.arrow.x += this.curSpeed;
            if (this.arrow.x >= 280) {
                this.isRigthDir = false;
            }
        } else {
            this.arrow.x -= this.curSpeed;
            if (this.arrow.x <= -280) {
                this.isRigthDir = true;
            }
        }
        this.countTime++;
    }

    private async refreshUI() {
        if (this.arrow.x < this.color.x + this.color.width / 2 &&
            this.arrow.x > this.color.x - this.color.width / 2) {
            GameUtil.playAnimation({ ske: this.ske, animName: "zha1", isLoop: false });
            await GameUtil.sleep(1000);
            this.setAttachment(false);
            // 成功继续
            this.curId++;
            if (this.curId > this.configs.length) {
                this.onCloseClicked();
                const talkData = StorageUtil.instance.getTalkData();
                talkData.id = 10906;
                HomeUI.instance.check();
                GameUI.instance.check();
                // 任务数据
                TaskModule.instance.saveData();
                SceneGame.instance.showToast(cc.v2(0, 0), '在你的努力下，妈妈的病有所好转');
            } else {
                await GameUtil.sleep(200);
                this.init();
            }
        } else {
            AudioManager.instance.playSound('扎针失败');
            this.hp--;
            this.refreshHp();
            this.setAttachment(true);
            if (this.hp <= 0) {
                this.onCloseClicked();
                SceneGame.instance.showToast(cc.v2(0, 0), '技术不到家啊，练练再回来重新诊治吧');
            } else {
                GameUtil.playAnimation({ ske: this.ske, animName: "zha2", isLoop: false });
                await GameUtil.sleep(2000);
                this.init();
                this.btnStart.active = true;
                this.setAttachment(false);
                GameUtil.playAnimation({ ske: this.ske, animName: "shou", isLoop: false });
            }
        }
    }

    public onCloseClicked() {
        // super.onCloseClicked();
        this.node.destroy();
        // HomeUI.instance.check();
        AudioManager.instance.playMusic(EMusicType.HomeBgm);
    }

    private onBtnsClicked(event: cc.Event.EventTouch, eventData: string) {
        const name = event.target.name;
        switch (name) {
            case "btnStart":
                {
                    this.isMove != this.isMove;
                    // 碰撞检测
                    if (this.isMove) {
                        this.isMove = false;
                        this.btnStart.active = false;
                        this.refreshUI();
                    } else {
                        this.isMove = true;
                    }
                }
                break;
        }
    }
}
AppService.instance.registViewData(VIEW_DATA);